﻿Public Class SPSortedWebCollection
    Implements IEnumerable
    Implements IEnumerator
    Private list As New ArrayList()
    Private index As Integer = -1
    Private [property] As String = ""


    Public Sub New(webs As SPWebCollection, [property] As String)
        Me.[property] = [property]

        For Each child As SPWeb In webs
            Add(child)
        Next

        Reset()
    End Sub
    Public Function GetEnumerator() As IEnumerator Implements IEnumerable.GetEnumerator
        Return Me
    End Function

    Public Function MoveNext() As Boolean Implements IEnumerator.MoveNext
        index += 1

        Return index < list.Count
    End Function

    Public Sub Add(web As SPWeb)
        list.Add(New SPSortedWeb(web, [property]))
    End Sub

    Public Sub Reset() Implements IEnumerator.Reset
        list.Sort()
        index = -1
    End Sub

    Public ReadOnly Property Current() Implements IEnumerator.Current
        Get
            Dim sw As SPSortedWeb = If((index < 0 OrElse index >= list.Count), Nothing, TryCast(list(index), SPSortedWeb))

            Return If(sw IsNot Nothing, sw.Web, Nothing)
        End Get
    End Property

    

    Protected Class SPSortedWeb
        Implements IComparable
        Private m_web As SPWeb = Nothing
        Private [property] As String = ""

        Public Sub New(web As SPWeb, [property] As String)
            Me.m_web = web
            Me.[property] = [property]
        End Sub

        Public ReadOnly Property Web() As SPWeb
            Get
                Return m_web
            End Get
        End Property

        Public Function CompareTo(obj As Object) As Integer Implements IComparable.CompareTo
            Dim sw As SPSortedWeb = TryCast(obj, SPSortedWeb)

            Dim val As String = SharePointHelper.GetPropertyCode(m_web, [property])
            Dim compareToVal As String = SharePointHelper.GetPropertyCode(sw.Web, [property])
            If SubWebs._sortOrder = 0 Then
                'sort ascending
                Return val.CompareTo(compareToVal)
            Else
                'sort descending
                Return compareToVal.CompareTo(val)
            End If
        End Function
    End Class



End Class



Public Class SharePointHelper
    Public Shared Function GetPropertyCode(web As SPWeb, [property] As String) As String

        'If web.AllProperties.ContainsKey([property]) Then
        '    Return web.AllProperties([property]).ToString

        'End If

        'sort by date or title
        If SubWebs._Sort = True Then
            Return web.Created.ToString
        Else
            Return web.Title.ToString
        End If

    End Function
End Class

